package com.sinoglobal.ningxia.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.view.listener.AbOnListViewListener;
import com.ab.view.pullview.AbPullListView;
import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.sinoglobal.networkconnections.HttpTools;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.amusement.AmusementActivity;
import com.sinoglobal.ningxia.activity.amusement.SettleDownActivity;
import com.sinoglobal.ningxia.activity.fm.FMActivity;
import com.sinoglobal.ningxia.activity.live.LiveHomeActivity;
import com.sinoglobal.ningxia.activity.mico.NewMicroAudioVisualActivity;
import com.sinoglobal.ningxia.activity.news.NewsDetailActivity;
import com.sinoglobal.ningxia.activity.news.NewsHomeActivity;
import com.sinoglobal.ningxia.adapter.GridViewHomeAdapter;
import com.sinoglobal.ningxia.adapter.HomeBannerAdapter;
import com.sinoglobal.ningxia.adapter.NewsAdapter;
import com.sinoglobal.ningxia.beans.HomeBannerBean;
import com.sinoglobal.ningxia.beans.HomeGridSortsVo;
import com.sinoglobal.ningxia.beans.HomeInfoVo;
import com.sinoglobal.ningxia.beans.HomeNewsBean;
import com.sinoglobal.ningxia.beans.NewsBean;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.ToastBuilder;
import com.sinoglobal.ningxia.widget.ChildViewPager;
import com.sinoglobal.shakeprize.utils.DispatchIntentHelper;
import com.sinoglobal.sinostore.SinoStore;
import com.sinoglobal.sinostore.activity.FirstActivity;
import com.sinoglobal.sinostore.system.Constants;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @author qiwx
 * @createdate 2014-6-9 上午9:11:19
 * @Description: 首页
 */

/**
 * TODO  在processData方法里根据pageNo是否等于来判断是否是加载,加载的话讲数据通过Adapter.addData()来添加
 */
public class HomeFragment extends Fragment implements OnClickListener,
        OnItemClickListener, AbOnListViewListener, OnPageChangeListener {
    int pageNo = 0, pageSize = 20;
    public View root;
    public LinearLayout main;
    // private ChildViewPager homeViewPager;// 首页banner图
    private ChildViewPager homeViewPager;// 首页banner图

    private HomeBannerAdapter bannerAdapter;// 首页banner图适配器
    ArrayList<HomeBannerBean> tvList;// banner数据源
    private TextView bannerInfo;// banner图提示信息
    private RadioGroup pointRadioGroup;// banner图下提示点
    ArrayList<RadioButton> radioButtons = new ArrayList<RadioButton>();// 存放banner里的
    private AbPullListView homeNews; // 新闻listview
    private View headView;// 头部
    private NewsAdapter newsAdapter;// 新闻适配器
    private List<NewsBean> newsData;
    /*
     * private TextView news;// 新闻 private TextView MicroAudioVisual;// 微视听
	 * private TextView enents;// 活动 private TextView entertainment;// 娱乐
	 * private TextView cate;// 美食 private TextView anju; // 安居 private TextView
	 * game;// 游戏 private TextView read;// 阅读 private TextView shop;// 阅读
	 */
    /**
     * @author xindz
     * @updatedate 2016年12月15日14:28:52
     * @desc 隐藏 商城,摇一摇等模块
     */
    private String[] array = {"新闻", "商城", "直播", "视频", "广播电视"};
    private int[] imgs = {R.drawable.icon_home_bt_news,
            R.drawable.icon_home_bt_shop, R.drawable.icon_home_bt_live,
            R.drawable.icon_home_bt_video, R.drawable.icon_home_bt_tv};
    private GridView gridView;
    private AsyncTask<Void, Void, HomeInfoVo> mTask;// 加载网络数据
    private int currentPagePosition;
    Thread autoThread;
    private boolean runing;
    private RequestCall requestCall;
    private ProgressDialog progressDialog;
    private ImageView iv_go_top;

	/*
     * private final String ENTERAINMENT_TYPE = "1"; private final String
	 * CATE_TYPE = "2";
	 */

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        root = inflater.inflate(R.layout.home_fragment_head, null);
        init(root, inflater);
        showListenter();
        initGridView();
        loadData();
        if (!AndPermission.hasPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                !AndPermission.hasPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // 申请权限。
            AndPermission.with(this)
                    .requestCode(1002)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .send();
        }
        autoThread = new Thread(new ThreadShow());
        autoThread.start();
        return root;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 只需要调用这一句，第一个参数是当前Acitivity/Fragment，回调方法写在当前Activity/Framgent。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1002)
    private void getLocationYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1002)
    private void getLocationNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1002).show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        runing = true;
        Log.i("dd", "" + runing);
    }

    @Override
    public void onPause() {
        super.onPause();
        runing = false;
        Log.i("dd", "" + runing);
    }

    // 初始化
    private void init(View root, LayoutInflater inflater) {
        homeNews = (AbPullListView) root.findViewById(R.id.Home_News);
        iv_go_top = (ImageView) root.findViewById(R.id.iv_go_top);
        iv_go_top.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                homeNews.smoothScrollToPosition(0, 0);
            }
        });
        homeNews.getHeaderView().setHeaderProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));
//        homeNews.setPullLoadEnable(false);

        homeNews.getFooterView().setFooterProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));

        TextView tvEmpty = (TextView) root.findViewById(R.id.tv1);

        tvEmpty.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                loadData();
            }
        });
        homeNews.setEmptyView(tvEmpty);
        headView = inflater.inflate(R.layout.home_fragment, null);
        gridView = (GridView) headView.findViewById(R.id.grid_view);
        /*
         * news = (TextView) headView.findViewById(R.id.program_news);
		 * MicroAudioVisual = (TextView)
		 * headView.findViewById(R.id.program_MicroAudioVisual); enents =
		 * (TextView) headView.findViewById(R.id.program_enents); entertainment
		 * = (TextView) headView.findViewById(R.id.program_entertainment); cate
		 * = (TextView) headView.findViewById(R.id.program_cate);
		 */
        // anju = (TextView) headView.findViewById(R.id.program_AnJu);

        // banner图滑动指示点
        pointRadioGroup = (RadioGroup) headView
                .findViewById(R.id.home_RadioGroup);
        bannerInfo = (TextView) headView.findViewById(R.id.viewPager_info);

        homeViewPager = (ChildViewPager) headView
                .findViewById(R.id.Banner_ViewPager);
        int screentWidth = FlyApplication.widthPixels;
        homeViewPager.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, screentWidth / 2));
        // homeViewPager.setOffscreenPageLimit(0);

        homeNews.addHeaderView(headView);
        newsAdapter = new NewsAdapter(getActivity(), null);
        homeNews.setAdapter(newsAdapter);
        headView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float dx = 0, dy = 0, ux, uy;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        dx = event.getX();
                        dy = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // deltaY > 0 是向下运动,< 0是向上运动
                        ux = event.getX();
                        uy = event.getY();
                        if (Math.abs(dx - ux) < Math.abs(dy - uy)) {
                            homeNews.onTouchEvent(event);
                        }
                }

                return false;
            }
        });
    }

    private void initGridView() {
        List<HomeGridSortsVo> data = new ArrayList<HomeGridSortsVo>();
        for (int i = 0; i < imgs.length; i++) {
            HomeGridSortsVo bean = new HomeGridSortsVo();
            bean.setName(array[i]);
            bean.setImgResId(imgs[i]);
            data.add(bean);
        }
        GridViewHomeAdapter gdAdapter = new GridViewHomeAdapter(getActivity(),
                R.layout.home_gridview_item, data);
        gridView.setAdapter(gdAdapter);
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                goHomeSort(getActivity(), position, view);
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (homeViewPager == null || tvList == null)
                return;
            if (msg.what == 1) {
                Log.i("dd", "viewPager");
                homeViewPager.setCurrentItem((++currentPagePosition)
                        % tvList.size());
            }
            super.handleMessage(msg);
        }

        ;
    };

    // 线程类
    class ThreadShow implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                if (runing) {
                    try {
                        Thread.sleep(5000);
                        // 需要做的事:发送消息
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        System.out.println("thread error...");
                    }
                }

            }
        }
    }

    public static void goHomeSort(final Context context, int pos, View view) {
        switch (pos) {
            // 新闻
            case 0:
                Intent news = new Intent(context, NewsHomeActivity.class);
                news.putExtra("TAG", "news");
                FlyUtil.intentForward(context, news);
                break;

            case 1:
                //商城
                Intent storeIntent = new Intent(context, FirstActivity.class);
                FlyUtil.intentForward(context, storeIntent);
                // 微视听
//                FlyUtil.intentForwardNetWork(context,
//                        MicroAudioVisualActivity.class);
                break;

            case 2:
                //直播
//                FlyUtil.intentForwardNetWork(context,
//                        VideoPlayerActivity.class);
                FlyUtil.intentForwardNetWork(context,
                        LiveHomeActivity.class);
                break;
            case 3:
                // 视频  (原先的微视听)
                FlyUtil.intentForwardNetWork(context,
                        NewMicroAudioVisualActivity.class);
//                FlyUtil.intentForwardNetWork(context,
//                        MicroAudioVisualActivity.class);
                break;

            case 4:
                //电视
//                FlyUtil.intentForwardNetWork(context, VideoActivity.class);
                // 广播
                FlyUtil.intentForwardNetWork(context, FMActivity.class);
                break;
            // 商城
            case 5:
//                Intent storeIntent = new Intent(context, FirstActivity.class);
//                FlyUtil.intentForward(context, storeIntent);
                break;
            // 摇一摇
            case 6:
                try {
                    DispatchIntentHelper.dispatchIntent(context, Constants.userCenterId);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                break;
            // 美食
            case 7:
                Intent intent1 = new Intent(context, AmusementActivity.class);
                intent1.putExtra(AmusementActivity.type, "2");
                FlyUtil.intentForward(context, intent1);
                break;
            // 安居
            case 8:
                FlyUtil.intentForwardNetWork(context, SettleDownActivity.class);
                break;
            // 娱乐
            case 9:
                Intent intent = new Intent(context, AmusementActivity.class);
                intent.putExtra(AmusementActivity.type, "1");
                FlyUtil.intentForward(context, intent);
                break;

        }
    }

    private void showListenter() {
        // enents.setOnClickListener(this);
        homeNews.setOnItemClickListener(this);
        homeNews.setAbOnListViewListener(this);
        homeViewPager.setOnPageChangeListener(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (requestCall != null) {
            HttpTools.getInstance().httpCancel(requestCall);
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        if (mTask != null)
            mTask.cancel(true);
        try {
            if (autoThread != null) {
                autoThread.interrupt();
                autoThread.stop();
            }
            autoThread = null;
        } catch (Exception e) {
            autoThread = null;
            e.printStackTrace();
        }

    }

    /**
     * @throws Exception
     * @author qiwx
     * @createdate 2014-7-9 下午1:21:35
     * @Description:加载数据
     * @type
     */
    private void loadData() {
        progressDialog = ProgressDialog.show(getActivity(), null, "正在加载", true, true);
        progressDialog.setCanceledOnTouchOutside(false);
        String url = "por=100";
        if (TextUtil.stringIsNotNull(FlyApplication.userId))
            url = url + "&userid=" + FlyApplication.userId;
        String urlResult = ConnectionUtil.getUrl(url);
        requestCall = HttpTools.getInstance().get(this, urlResult);
        requestCall.execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                homeNews.stopRefresh();
                homeNews.stopLoadMore();
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    HomeInfoVo homeInfoVo = JSON.parseObject(response, HomeInfoVo.class);
                    Logger.json(response);
                    homeNews.stopRefresh();
                    homeNews.stopLoadMore();
                    processData(homeInfoVo);
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "网络异常,请重试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void loadMoreData() {
        ResultCallback newsLoadMoreCallback = new ResultCallback(getActivity()) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                homeNews.stopLoadMore();
                homeNews.stopRefresh();
                HomeNewsBean homeNewsBean = JSON.parseObject(response, HomeNewsBean.class);
                processLodData(homeNewsBean);
            }

            @Override
            public void onErrorCode(Exception e) {
                super.onErrorCode(e);
                homeNews.stopRefresh();
                homeNews.stopLoadMore();
            }
        };
        RemoteImpl.getInstance().getHomeNews(this, pageNo, 10).execute(newsLoadMoreCallback);

    }

    /**
     * 处理刷新数据
     *
     * @param result
     */
    private void processData(HomeInfoVo result) {
        if (result == null)
            return;
        if (result.getCode() == Code.CODE_SUCCESS) {
            FlyApplication.jiFen = result.getScore();
            Intent jifen = new Intent(MContants.BROADCAST_JIFEN);
            getActivity().sendBroadcast(jifen);
            SharedPreferenceUtil.saveString(getActivity(), "jifen",
                    result.getScore());
            SinoStore.initScore(result.getScore());

            tvList = result.getBanners();
            if (tvList != null && tvList.size() > 0) {
                if (getActivity() == null)
                    return;
                if (pointRadioGroup != null)
                    pointRadioGroup.removeAllViews();
                if (radioButtons != null && radioButtons.size() > 0)
                    radioButtons.clear();
                for (int i = 0, lenth = tvList.size(); i < lenth; i++) {
                    RadioButton radioButton = (RadioButton) LayoutInflater
                            .from(FlyApplication.context).inflate(
                                    R.layout.radiobutton, null);
                    radioButtons.add(radioButton);
                    radioButton
                            .setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(
                                        CompoundButton buttonView,
                                        boolean isChecked) {
                                    if (isChecked) {
                                        homeViewPager
                                                .setCurrentItem(radioButtons
                                                        .indexOf(buttonView));
                                    }
                                }
                            });
                    pointRadioGroup.addView(radioButton);
                    if (i == 0) {
                        radioButton.setChecked(true);
                    }
                }

                if (pointRadioGroup.getChildCount() > 1) {
                    pointRadioGroup.setVisibility(View.VISIBLE);
                } else {
                    pointRadioGroup.setVisibility(View.GONE);
                }

                bannerInfo.setText(tvList.get(currentPagePosition)
                        .getIntro());
                radioButtons.get(currentPagePosition).setChecked(true);
                bannerAdapter = new HomeBannerAdapter(getActivity(),
                        tvList);
                homeViewPager.setAdapter(bannerAdapter);
                bannerInfo.setText(tvList.get(0).getIntro());

                // homeViewPager.setBackgroundDrawable(null);
            }

            newsData = result.getNews();
            if (newsData != null && newsData.size() > 0) {
                newsAdapter = new NewsAdapter(getActivity(), newsData);
                homeNews.setAdapter(newsAdapter);
                Logger.i("刷新的时候设置数据到Adapter");
            }
        }
    }

    private void processLodData(HomeNewsBean bean) {
        if (bean != null) {
            if (bean.getCode() == 0) {
                List<NewsBean> newsBean2List = bean.getList();
                if (newsBean2List != null) {
                    newsAdapter.addData(newsBean2List);
                }
            } else {
                ToastBuilder.getIntance(FlyApplication.context).showToast(bean.getMessage());
            }

        }

    }

    @Override
    public void onClick(View v) {
    }

    // News ListView item点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        NewsBean bean = new NewsBean();
        bean.setId(newsData.get(position).getId());
        Intent go = new Intent(getActivity(), NewsDetailActivity.class);
        go.putExtra(NewsBean.class.getName(), bean);
        getActivity().startActivity(go);
    }

    @Override
    public void onRefresh() {
        Logger.e("onRefresh");
        pageNo = 0;
        loadData();
    }

    @Override
    public void onLoadMore() {
        Logger.e("onLoadMore--------------------------------------------------------------------------");
        pageNo++;
        loadMoreData();
    }

    // ViewPager监听
    @Override
    public void onPageSelected(int position) {
        currentPagePosition = position;
        bannerInfo.setText(tvList.get(position % tvList.size()).getIntro());
        radioButtons.get(position % tvList.size()).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

}
